package org.idea.servlet;

import com.google.gson.Gson;
import org.idea.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zqx
 * @Date 2023-10-26
 */
@WebServlet("/getUserList.do")
public class GetAllUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        // 模拟 DAO 向数据库查询数据
        User user1 = new User("张三", "123123");
        User user2 = new User("李四", "123123");
        User user3 = new User("王五", "123123");

        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);

        PrintWriter out = resp.getWriter();

        String json = new Gson().toJson(list);
        out.print(json);
        System.out.println(json);

        out.flush();
        out.close();

    }
}
